﻿using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Data.Extensions;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Ioc;
using RestSharp;
using System.Windows;
using MessageBox = System.Windows.Forms.MessageBox;

namespace ModuleTonyMES.ViewModels
{
    public class MESMainViewModel : NavigationViewModel
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        string partNum = string.Empty;
        //string connetString = "http://prod-webiis-02.tonytech.com:8070/MachineData.asmx/";
        //string connetString1 = "http://prod-webiis-02.tonytech.com:8012/GetSN_Det.asmx/";
        string connetString = "http://prod-webiis-02.tonytech.com:9030/MachineData.asmx/";
        string connetString1 = "http://prod-webiis-02.tonytech.com:9035/GetSN_Det.asmx/";
        private RestClient client, snclient;
        #endregion
        #region 属性
        private string messageStr;
        public string MessageStr
        {
            get { return messageStr; }
            set { SetProperty(ref messageStr, value); }
        }
        private string machineCode;
        public string MachineCode
        {
            get { return machineCode; }
            set { SetProperty(ref machineCode, value); }
        }
        private string processCode;
        public string ProcessCode
        {
            get { return processCode; }
            set { SetProperty(ref processCode, value); }
        }
        private bool isUseMES;
        public bool IsUseMES
        {
            get { return isUseMES; }
            set { SetProperty(ref isUseMES, value); }
        }
        private string uPLotNo;
        public string UPLotNo
        {
            get { return uPLotNo; }
            set { SetProperty(ref uPLotNo, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));
        private DelegateCommand<object> mESSwitchCommand;
        public DelegateCommand<object> MESSwitchCommand =>
            mESSwitchCommand ?? (mESSwitchCommand = new DelegateCommand<object>(ExecuteMESSwitchCommand));
        private DelegateCommand updateLotNoCommand;
        public DelegateCommand UpdateLotNoCommand =>
            updateLotNoCommand ?? (updateLotNoCommand = new DelegateCommand(ExecuteUpdateLotNoCommand));

        async void ExecuteUpdateLotNoCommand()
        {
            try
            {
                var str = UPLotNo.Replace(" ", "");
                if (str != string.Empty)
                {
                    if (await CheckLot(str))
                    {
                        addMessage($"更新料号\"{partNum}\"");

                        aggregator.SendMessage($"PartNumChanged;{partNum}", "Run");
                    }
                }
                else
                {
                    MessageBox.Show("Lot号不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            {
                using var mdb = new MDbContext(partNum);
                var param = mdb.MParams.FirstOrDefault(p => p.Name == "UPLotNo");
                if (param != null)
                {
                    param.Value = UPLotNo;
                    mdb.SaveChanges();
                }
            }
        }
        void ExecuteMESSwitchCommand(object obj)
        {
            if (obj is bool r)
            {
                using var mdb = new MDbContext(partNum);
                var param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
                if (param != null)
                {
                    param.Value = IsUseMES.ToString();
                }
                else
                {
                    mdb.MParams.Add(new MParam { Name = "IsUseMES", Value = IsUseMES.ToString(), Type = typeof(bool).Name, Hand = 0 });
                }
                mdb.SaveChanges();
            }
        }
        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            if (obj is string str)
            {
                switch (str)
                {
                    case "MachineCode":
                        {
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "MachineCode");
                            if (param != null)
                            {
                                param.Value = MachineCode;
                            }
                            else
                            {
                                mdb.MParams.Add(new MParam { Name = "MachineCode", Value = MachineCode, Type = typeof(string).Name, Hand = 0 });                                
                            }
                            mdb.SaveChanges();
                        }
                        break;
                    case "ProcessCode":
                        {
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "ProcessCode");
                            if (param != null)
                            {
                                param.Value = ProcessCode;
                            }
                            else
                            {
                                mdb.MParams.Add(new MParam { Name = "ProcessCode", Value = ProcessCode, Type = typeof(string).Name, Hand = 0 });
                            }
                            mdb.SaveChanges();
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion
        #region 构造函数
        public MESMainViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            MessageStr = string.Empty;
            client = new RestClient(connetString);
            snclient = new RestClient(connetString1);
            aggregator.ResgiterMessage(arg =>
            {
                switch (arg.Message)
                {
                    case "AppClose":
                        {
                            //if (source0 != null)
                            //{
                            //    source0.Cancel();
                            //}
                        }
                        break;

                    default:
                        break;
                }
            });
            aggregator.ResgiterMessage(arg =>
            {
                var strs = arg.Message.Split(new char[] { ';' });
               
                switch (strs[0])
                {
                    case "PartNum":
                        {
                            partNum = strs[1];
                            addMessage($"料号:{partNum}");
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "MachineCode");
                            if (param != null)
                            {
                                MachineCode = param.Value;
                            }
                            else
                            {
                                MachineCode = "DD-CS-JGHJ-002";
                                mdb.MParams.Add(new MParam { Name = "MachineCode",Value = MachineCode, Type = typeof(string).Name,Hand = 0});
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "ProcessCode");
                            if (param != null)
                            {
                                ProcessCode = param.Value;
                            }
                            else
                            {
                                ProcessCode = "NE208";
                                mdb.MParams.Add(new MParam { Name = "ProcessCode", Value = ProcessCode, Type = typeof(string).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "UPLotNo");
                            if (param != null)
                            {
                                UPLotNo = param.Value;
                            }
                            else
                            {
                                UPLotNo = "N23040073";
                                mdb.MParams.Add(new MParam { Name = "UPLotNo", Value = UPLotNo, Type = typeof(string).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
                            if (param != null)
                            {
                                IsUseMES = bool.Parse(param.Value);
                            }
                            else
                            {
                                IsUseMES = true;
                                mdb.MParams.Add(new MParam { Name = "IsUseMES", Value = IsUseMES.ToString(), Type = typeof(bool).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "UpLoad":
                        {
                            if (IsUseMES)
                            {
                                try
                                {
                                    List<Comparison> records = JsonConvert.DeserializeObject<List<Comparison>>(arg.Message.Substring(arg.Message.IndexOf(";") + 1, arg.Message.Length - (arg.Message.IndexOf(";") + 1)));
                                    List<string> barcodes = new List<string>();
                                    foreach (var item in records)
                                    {
                                        if (!barcodes.Contains(item.条码) && item.条码 != string.Empty)
                                        {
                                            barcodes.Add(item.条码.Substring(0, item.条码.Length));
                                        }
                                    }
                                    if (barcodes.Count > 0)
                                    {
                                        foreach (var bar in barcodes)
                                        {
                                            var _records = records.Where(p => p.条码 == bar);
                                            if (_records.Any())
                                            {
                                                UpLoad(bar, _records.ToArray());
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    addMessage(ex.Message);
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }, "MES");
            addMessage("加载完成");
        }
        #endregion
        #region 功能函数
        private void addMessage(string str)
        {
            logger.Debug("MES:" + str);
            string[] s = MessageStr.Split('\n');
            if (s.Length > 1000)
            {
                MessageStr = "";
            }
            if (MessageStr != "")
            {
                MessageStr += "\n";
            }
            MessageStr += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + str;
        }
        void UpLoad(string barcode,Comparison[] _records)
        {
            #region position
            string paramAll = "type!position";
            for (int i = 0; i < _records.Length; i++)
            {
                paramAll += $"|{i + 1}!{_records[i].焊接点}";
            }
            List<Parameter1> parm = new List<Parameter1>();
            parm.Add(new Parameter1
            {
                Name = "SN",
                Value = barcode
            });
            parm.Add(new Parameter1
            {
                Name = "MachineCode",
                Value = MachineCode
            });
            parm.Add(new Parameter1
            {
                Name = "ProcessCode",
                Value = ProcessCode
            });
            parm.Add(new Parameter1
            {
                Name = "ParameterAll",
                Value = paramAll
            });
            var res = Execute_MachineData(new BaseRequest
            {
                Method = Method.Post,
                Route = "MachineData",
                ContentType = "application/x-www-form-urlencoded",
                Parameters = parm
            });
            if (!res)
            {
                addMessage("MES:position上传异常");
            }
            else
            {
                addMessage("MES:position上传成功");
            }
            #endregion
            #region power
            paramAll = "type!power";
            for (int i = 0; i < _records.Length; i++)
            {
                paramAll += $"|{i + 1}!{_records[i].功率}";
            }
            parm.Clear();
            parm.Add(new Parameter1
            {
                Name = "SN",
                Value = barcode
            });
            parm.Add(new Parameter1
            {
                Name = "MachineCode",
                Value = MachineCode
            });
            parm.Add(new Parameter1
            {
                Name = "ProcessCode",
                Value = ProcessCode
            });
            parm.Add(new Parameter1
            {
                Name = "ParameterAll",
                Value = paramAll
            });
            res = Execute_MachineData(new BaseRequest
            {
                Method = Method.Post,
                Route = "MachineData",
                ContentType = "application/x-www-form-urlencoded",
                Parameters = parm
            });
            if (!res)
            {
                addMessage("MES:power上传异常");
            }
            else
            {
                addMessage("MES:power上传成功");
            }
            #endregion
            #region speed
            paramAll = "type!speed";
            for (int i = 0; i < _records.Length; i++)
            {
                paramAll += $"|{i + 1}!{_records[i].速度}";
            }
            parm.Clear();
            parm.Add(new Parameter1
            {
                Name = "SN",
                Value = barcode
            });
            parm.Add(new Parameter1
            {
                Name = "MachineCode",
                Value = MachineCode
            });
            parm.Add(new Parameter1
            {
                Name = "ProcessCode",
                Value = ProcessCode
            });
            parm.Add(new Parameter1
            {
                Name = "ParameterAll",
                Value = paramAll
            });
            res = Execute_MachineData(new BaseRequest
            {
                Method = Method.Post,
                Route = "MachineData",
                ContentType = "application/x-www-form-urlencoded",
                Parameters = parm
            });
            if (!res)
            {
                addMessage("MES:speed上传异常");
            }
            else
            {
                addMessage("MES:speed上传成功");
            }
            #endregion
            #region height
            paramAll = "type!height";
            for (int i = 0; i < _records.Length; i++)
            {
                paramAll += $"|{i + 1}!{_records[i].焦距}";
            }
            parm.Clear();
            parm.Add(new Parameter1
            {
                Name = "SN",
                Value = barcode
            });
            parm.Add(new Parameter1
            {
                Name = "MachineCode",
                Value = MachineCode
            });
            parm.Add(new Parameter1
            {
                Name = "ProcessCode",
                Value = ProcessCode
            });
            parm.Add(new Parameter1
            {
                Name = "ParameterAll",
                Value = paramAll
            });
            res = Execute_MachineData(new BaseRequest
            {
                Method = Method.Post,
                Route = "MachineData",
                ContentType = "application/x-www-form-urlencoded",
                Parameters = parm
            });
            if (!res)
            {
                addMessage("MES:height上传异常");
            }
            else
            {
                addMessage("MES:height上传成功");
            }
            #endregion
        }
        async Task<bool> Execute_MachineDataAsync(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Route, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameters != null)
            {
                foreach (var param in baseRequest.Parameters)
                {
                    request.AddParameter(param.Name, param.Value);
                }
            }
            var response = await client.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return response.Content.Contains("OK");
            else
                return false;
        }
        bool Execute_MachineData(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Route, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameters != null)
            {
                foreach (var param in baseRequest.Parameters)
                {
                    request.AddParameter(param.Name, param.Value);
                }
            }
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return response.Content.Contains("OK");
            else
                return false;
        }
        async Task<bool> CheckLot(string str)
        {
            List<Parameter1> parm = new List<Parameter1>();
            parm.Add(new Parameter1
            {
                Name = "RCNO",
                Value = str
            });
            try
            {
                var request = new RestRequest("GetRCNO_Part", Method.Post);
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                foreach (var item in parm)
                {
                    request.AddParameter(item.Name, item.Value);
                }
                var response = await snclient.ExecuteAsync(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var res = JsonConvert.DeserializeObject<Tony_GetSN_RCNO>(response.Content);
                    addMessage($"res:{res.res};msg:{res.msg};part_no:{res.part_no}");
                    if (res.res == "OK")
                    {
                        if (partNum != res.part_no)
                        {
                            partNum = res.part_no;
                        }
                        else
                        {
                            addMessage($"料号\"{res.part_no}\"就是当前料号");
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    addMessage("请求失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                addMessage(ex.Message);
                return false;
            }
            return true;
        }
        #endregion
    }
    class BaseRequest
    {
        public Method Method { get; set; }
        public string Route { get; set; }
        public string ContentType { get; set; } = "application/x-www-form-urlencoded";
        public List<Parameter1> Parameters { get; set; }
    }
    public class Parameter1
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
    public class Tony_GetSN_RCNO
    {
        public string res { get; set; }
        public string msg { get; set; }
        public string part_no { get; set; }
    }
}
